#!/usr/bin/env python 

#  
#  Copyright (C) 2009-2010 Francis Belanger
# 
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
# 
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
# 
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
 
import atexit
import gobject
import glib
import dbus
import dbus.glib
import sys
import os
import traceback


try:
	from dockmanager.dockmanager import DockManagerItem, DockManagerSink
	from dockmanager.dockmanager import RESOURCESDIR, DOCKITEM_IFACE
	from signal import signal, SIGTERM
	from sys import exit
except ImportError, e:
	print e
	print traceback.extract_stack()
 	exit()

quodlibetbus = 'net.sacredchao.QuodLibet'
quodlinetpath = '/net/sacredchao/QuodLibet'

class QuodLibetItem(DockManagerItem):
	def __init__(self, sink, path):

		DockManagerItem.__init__(self, sink, path)

		self.bus = dbus.SessionBus() 
                
		self.bus.add_signal_receiver(self.name_owner_changed_cb,
                                             dbus_interface='org.freedesktop.DBus',
                                             signal_name='NameOwnerChanged')

		
	
	        self.bus.add_signal_receiver(self.song_changed, 'SongStarted', 'net.sacredchao.QuodLibet') 
          	self.bus.add_signal_receiver(self.song_changed, 'Paused', 'net.sacredchao.QuodLibet') 
          	self.bus.add_signal_receiver(self.song_changed, 'Unpaused', 'net.sacredchao.QuodLibet') 
     
		self.add_menu_item("Previous", "media-skip-backward", "QuodLibet Controls")
 		self.add_menu_item("Play/Pause", "media-playback-start", "QuodLibet Controls")
 		self.add_menu_item("Next", "media-skip-forward", "QuodLibet Controls")

		#if self.player:
			#self.song_changed()

	def name_owner_changed_cb(self, name, old_owner, new_owner):
		if name == quodlibetbus:
			if new_owner:
				self.player = self.bus.get_object(quodlibetbus, quodlinetpath) 
			else:
				self.player = None
				self.control = None
				self.song_changed()

	def menu_pressed(self, menu_id):
		if self.id_map[menu_id] == "Play/Pause":
			os.system("quodlibet --play-pause")
		elif self.id_map[menu_id] == "Next":
			os.system("quodlibet --next")
		elif self.id_map[menu_id] == "Previous":
			os.system("quodlibet --previous")

	def update_icon(self):
		if self.player:
			if self.player.IsPlaying():
				self.set_icon("/home/%s/.quodlibet/current.cover" % os.getenv('USERNAME'))
				return True
		else:
			self.reset_icon()

	def update_tooltip(self):
		if self.player:
			if self.player.IsPlaying(): 
				track = self.player.CurrentSong()
				title = track.get('title', None) 
				album = track.get('album', None) 
				artist = track.get('artist', None)
				self.songinfo = "%s - %s" % (artist, title)
				print self.songinfo
				self.set_tooltip(self.songinfo)
			else:
				self.reset_tooltip()

	def update_badge(self):
		if self.player:
			if self.player.IsPlaying(): 
				track = self.player.CurrentSong()
				title = track.get('title', None) 
				album = track.get('album', None) 
				artist = track.get('artist', None)
				self.songinfo = "%s - %s" % (artist, title)
				print self.songinfo
				self.set_badge(self.songinfo)
		else:
			self.reset_badge()
		
	def song_changed(self, state=None):
		self.update_icon()
		self.update_tooltip()
		#self.update_badge()
	
	

class QuodLibetSink(DockManagerSink):
	def item_path_found(self, pathtoitem, item):
		if item.Get(DOCKITEM_IFACE, "DesktopFile", dbus_interface="org.freedesktop.DBus.Properties").endswith ("quodlibet.desktop"):
			self.items[pathtoitem] = QuodLibetItem(self, pathtoitem)
 
quodlibetsink = QuodLibetSink()
 
def cleanup():
	quodlibetsink.dispose()
 
if __name__ == "__main__":
	mainloop = gobject.MainLoop(is_running=True)
 
	atexit.register(cleanup)
	signal(SIGTERM, lambda signum, stack_frame: exit(1))
 
	mainloop.run()
